from flask import Flask
from flask import request, session, redirect, make_response
from flask import url_for
from flask import render_template
from flask import g
from markupsafe import escape

import sqlite3
import time
import config
app = Flask(__name__)
app.config.from_object('config')
app.config.from_envvar('FLASK_SETTINGS', silent=True)


@app.before_request
def before_request():
    g.db = sqlite3.connect(app.config['DATABASE'])

@app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()


@app.route('/R')
@app.route('/R/<int:r>')
def getR(r):
    return render_template('getR.html', R=r)

@app.route('/U')
@app.route('/U/<int:u>')
def getU(u):
    return render_template('getU.html', U=u)

@app.route('/')
@app.route('/<name>')
def getname(name=None):
    if name == None:
        name = 'world'
    if name == 'xwh':
        return 'Hey, %s' % name
    return f"Hello, {escape(name)}!"

@app.route('/<int:user_id>')
def getid(user_id):
    return 'The ID is %d' % user_id

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        name = request.form['user']
        passwd = request.form['passwd']
        cursor = g.db.execute('select * from users where name=? and password=?', [name, passwd])
        if cursor.fetchone() is not None:
            session['user'] = name
            response = make_response('Login successfully!')
            response.set_cookie('login_time', time.strftime('%Y-%m-%d %H:%M:%S'))
        else:
            response = make_response('No such user!')

    else:
        if 'user' in session:
            login_time = request.cookies.get('login_time')
            response = make_response('Hello %s, you logged in on %s' % (session['user'], login_time))
        else:
            title = request.args.get('title', 'client')
            response = make_response(render_template('login.html', title=title), 200)
            response.headers['key'] = 'value'

    return response

app.secret_key = '123456'

@app.route('/logout')
def logout():
    session.pop('user', None)
    return redirect(url_for('login'))

@app.route('/path')
def path():
    #return url_for('login', ID='111')
    return url_for('getname', name='man')
    #return url_for('static', filename='style.css')

with app.test_request_context():
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('getid', user_id=123))

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)